/*
 * CDContentPanel.cpp
 *
 *  Created on: 2011-2-27
 *      Author: yangbo
 */
#include "CDContentPanel.h"
#include <wx/dcclient.h>
#include <wx/app.h>
#include "BootCDCheckerMain.h"
#include "BootCDCheckerApp.h"
#include <wx/caret.h>

BEGIN_EVENT_TABLE(CDContentPanel, wxWindow)
	EVT_PAINT 	( CDContentPanel::OnPaint)
//	EVT_SIZE	( CDContentPanel::OnSize)
//	EVT_ERASE_BACKGROUND( CDContentPanel::OnEraseBackground)
END_EVENT_TABLE()

// 要放到一个 wxScrolledWindow 中才能正常绘制。
CDContentPanel::CDContentPanel(wxWindow *parent) :
			wxWindow(parent, wxID_ANY),
			m_cdReader(NULL)
{
    // reduce flicker if wxEVT_ERASE_BACKGROUND is not available
    SetBackgroundColour(*wxLIGHT_GREY);
    wxCaret* pCaret = GetCaret();
//    if(pCaret)
//    	pCaret->Show(true);
}

CDContentPanel::~CDContentPanel()
{
	// TODO Auto-generated destructor stub
}

void CDContentPanel::OnPaint(wxPaintEvent& event)
{
	/*
	If you define a paint event handler, you must always create a wxPaintDC object,
	even if you don’t use it. Creating this object will tell wxWidgets that the
	invalid regions in the window have been repainted so that the windowing sys-
	tem won’t keep sending paint events ad infinitum.
	*/
    wxPaintDC dc(this);
    if(m_cdReader)
    {
    	wxUint8* pBuf;
    	size_t readedCnt = m_cdReader->ReadSection(1, &pBuf);
    	wxString content;
    	for(int i=0; i<readedCnt; i++)
    	{
    		wxString sec;
    		sec.Printf(_T("%02x "), pBuf[i]);
    		content << sec;
    		if((i+17)%16 == 0)
    		{
    			content << _T("\n");
    		}
    	}
    	dc.SetPen(*wxBLACK_PEN);
    	dc.DrawText(content, 0, 0);
    }
}

void CDContentPanel::OnEraseBackground(wxEraseEvent& event)
{

}

void CDContentPanel::SetCDReader(ELTReader *cdReader)
{
	if(m_cdReader)
	{
		delete m_cdReader;
	}
	m_cdReader = cdReader;
	wxSize size = CalculateWinSizeFromFile(m_cdReader->GetTotalLength());

	SetMinSize(size); 	// 不能用 SetSize() 应为 sizer 会重新计算并设置本 window 的size.
	wxScrolledWindow* sw = (wxScrolledWindow*) GetParent();
	sw->FitInside();	// 让splitter计算内部窗口大小，更新滚动条的显示。
	Refresh();
}

wxSize CDContentPanel::CalculateWinSizeFromFile(wxFileOffset fileSize)
{
	wxUint16 horzSize = 16;
	wxUint32 sectCount = fileSize / horzSize;
	wxClientDC cdc(this);
	wxSize te = cdc.GetTextExtent(_T("00 "));

	te.x *= horzSize;
	te.y *= sectCount;
	if(te.y<=0)
		te.y = INT_MAX/2;

	return te;
}

void CDContentPanel::OnSize(wxSizeEvent& event)
{

}

wxSize CDContentPanel::GetScrollSize()
{
	wxClientDC cdc(this);
	return cdc.GetTextExtent(_T("00 "));
}
